package com.supersoul.myself.service.impl;

import com.alibaba.fastjson.JSON;
import com.supersoul.myself.cache.TokenCache;
import com.supersoul.myself.dao.UserDao;
import com.supersoul.myself.entity.User;
import com.supersoul.myself.entity.vo.LoginVO;
import com.supersoul.myself.ex.ServiceException;
import com.supersoul.myself.service.UserService;
import com.supersoul.myself.util.SmsUtil;
import com.supersoul.myself.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public User login(LoginVO loginVO) throws ServiceException {
        // 根据手机号获取短信验证码
        String code = stringRedisTemplate.opsForValue().get(loginVO.getPhone());
        code = "111111";
        if (loginVO.getCode().equals(code)) {
            User user = userDao.findByPhone(loginVO.getPhone());
            if (user == null) {
                // 注册用户
                user = new User();
                user.setPhone(loginVO.getPhone());
                user.buildCreate();
                userDao.save(user);
            }
            String token = UUIDUtils.generateUUID() + System.currentTimeMillis();
            // 将token加入本地缓存中
            stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(user), 7*24*60*60*1000, TimeUnit.MILLISECONDS);
            user.setToken(token);
            return user;
        } else {
            return null;
        }
    }

    /**
     * 获取短信验证法
     * @param phone
     * @throws ServiceException
     */
    @Override
    public void codeToPhone(String phone) throws Exception {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        log.info("code={}", code);
        code =  111111;
        stringRedisTemplate.opsForValue().set(phone, String.valueOf(code), 5*60*1000, TimeUnit.MILLISECONDS);
        // 异步给手机发送短信
//        int finalCode = code;
//        Thread thread = new Thread(() -> {
//            try {
//                SmsUtil.sendSms(phone, String.valueOf(finalCode));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
//        thread.start();

    }


}
